<?php
/**
 * UM Meta Boxes Class
 * - handles the creation, display, and
 * - modification of meta boxes
 * 
 * @author Sam
 * @since Urban Meandering 1.0
 */
class UM_Meta_Boxes {
  protected $_meta_box;
  
  //Create meta box based on given data
  function __construct( $meta_box )
  {
    $this->_meta_box = $meta_box;
    
    add_action( 'add_meta_boxes', array( &$this, 'add' ) ); //add meta box, using 'add_meta_boxes' for WP 3.0+
    add_action( 'save_post', array( &$this, 'save' ) );
  }
  
  //Add meta box for multiple post types
  function add()
  {
    foreach( $this->_meta_box['pages'] as $page )
    {
      global $post;
      
      add_meta_box( 
        $this->_meta_box['id'], 
        $this->_meta_box['title'], 
        array( &$this, 'show' ),
        $page, 
        $this->_meta_box['context'], 
        $this->_meta_box['priority']
      );
    }
  }
  
  //Callback function to show fields in meta box
  function show()
  { 
    global $post;
    
    //Use nonce for verification
    echo '<input type="hidden" name="meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
    
    echo '<table class="form-table">';
    
    foreach( $this->_meta_box['fields'] as $field )
    {
      // get current post meta data
			$meta = get_post_meta($post->ID, $field['id'], $field['single-valued']);
      
      echo '<tr>';
			
			if ( $field['name'] )
			{
				if ( $this->_meta_box['context'] == 'normal' )
					echo '<th style="width:30%"><label for="', $field['id'], '">', $field['name'], '</label></th>';
				elseif ( $this->_meta_box['context'] == 'side' )
					echo '<th style="width:40%"><label for="', $field['id'], '">', $field['name'], '</label></th>';
			}
        
			echo '<td>';
      
      switch( $field['type'] )
      {
        case 'text':
				{
					echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : '', '" size="30" style="width:97%" />',
							'<br />', $field['desc'];
				}
				break;
				
				case 'multitext':
				{
					$meta_count = 0;
					
					if ( $meta )
					{
						$meta = current( $meta );
						
						if ( is_array($meta) && count($meta) > 0 )
						{
							foreach( $meta as $item )
							{
								echo '<p>';
								
								echo '<span><input type="text" name="' , $field['id'] , '[' , $meta_count , ']" value="' , $item , '" /></span>';
								echo '<a class="remove_textfield" style="cursor:pointer;">Remove</a>';
								
								echo '</p>';
								$meta_count++;
							}
						}
					}
					
					echo '<span id="textfield_append_here"></span>';
					echo '<a class="add_more_textfield" style="cursor:pointer">Add More</a>';
					?>
					
					<script type="text/javascript">
						jQuery(document).ready(function($) {
							var textfieldMetaCount = <?php echo $meta_count; ?>;
							var textfieldID = '<?php echo $field['id']; ?>';
							var textfieldName = '<?php echo $field['name']; ?>';
							
							$('.add_more_textfield').click(function() {
								var html = '<p>' + 
															'<span>' + 
																'<input type="text" name="' + textfieldID + '['+textfieldMetaCount+']" />' + 
															'</span>' + 
															'<a class="remove_textfield" style="cursor:pointer;">Remove</a>' + 
														'</p>';
								
								$('#textfield_append_here').append(html);
								
								textfieldMetaCount++;
							});
							
							$('.remove_textfield').live('click', function() {
								$(this).parent().remove();
							});
						});
					</script>
					
					<?php
				}
				break;
				
				case 'tinymce':
				{
					echo $field['desc'];
					
					wp_editor( 
						$meta, 
						$field['id'],
						$field['tinymce-settings']
					);
				}
				break;
				
        case 'textarea':
				{
					echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : '', '</textarea>',
							'<br />', $field['desc'];
				}
				break;
				
        case 'select':
				{
						echo '<span>' , $field['desc'] , '</span>';
						echo '<br />';
            echo '<select name="', $field['id'], '" id="', $field['id'], '">';
            foreach ($field['options'] as $option) {
                echo '<option', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
            }
            echo '</select>';
				}
				break;
				
        case 'radio':
				{
          $is_checked = ''; 
					foreach ($field['options'] as $key => $value) {
						$checked = '';
						
						if ( $meta == $key )
						{
							$checked = 'checked="yes"';
							$is_checked = 'yes';
							echo '<input type="radio" id="', $key, '" name="', $field['id'], '" value="', $key, '"', $checked, ' />', '<label for="', $key, '">', $value, '</label><br />';
						}
						elseif ( $field['std'] == $key && $is_checked == '' )
						{
							$checked = 'checked="yes"';
							$is_checked = 'yes';
							echo '<input type="radio" id="', $key, '" name="', $field['id'], '" value="', $key, '"', $checked, ' />', '<label for="', $key, '">', $value, '</label><br />';
						}
						else
						{
							echo '<input type="radio" id="', $key, '" name="', $field['id'], '" value="', $key, '"', ' />', '<label for="', $key, '">', $value, '</label><br />';
						}
					}
				}
				break;
				
        case 'checkbox':
				{
					echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
				}
				break;
      }
      
      echo '</td>',
        '</tr>';
    }
    
    echo '</table>';
  }
  
  //Save data from meta box
  function save( $post_id )
  {
    // verify nonce
    if ( ! wp_verify_nonce(isset($_POST['meta_box_nonce']) ? $_POST['meta_box_nonce'] : '', basename(__FILE__))   )
    {
      return $post_id;
    }
   
    // check autosave (don't save on autosave)
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) 
    {
      return $post_id;
    }
    
    // check permissions
    if ('page' == $_POST['post_type']) 
		{
      if (!current_user_can('edit_page', $post_id)) 
      {
          return $post_id;
      }
    } 
    elseif (!current_user_can('edit_post', $post_id)) 
    {
      return $post_id;
    }
    
    foreach( $this->_meta_box['fields'] as $field ) 
    {
			$old = get_post_meta($post_id, $field['id'], $field['single-valued']);
      $new = $_POST[$field['id']];
			
			if ( $field['single-field'] )
      {
				if ($new && $new != $old) 
				{
						update_post_meta($post_id, $field['id'], $new);
				} 
				elseif ('' == $new && $old) 
				{
						delete_post_meta($post_id, $field['id'], $old);
				}
			}
			else
      { 
        delete_post_meta($post_id, $field['id']);
				
        if ($new && count($new) > 0)
        {
          foreach( $new as $key => $values )
          {
            $unset = true;

            foreach( $values as $value )
            {
              if ( ! empty( $value ) )
                $unset = false;
            }

            if ( $unset )
              unset( $new[$key] );
          }
        }
        
        if ( $new )
        {
          update_post_meta($post_id, $field['id'], $new);
        }
      }
    }
  }
}

//prefix of meta keys to avoid duplicate ids (optional)
$prefix = '_um_';

$meta_boxes = array();

/**
 * Menu Meta Box
 */
$meta_boxes[] = array(
	'id' => 'food-menu',
	'title' => 'Menu',
	'pages' => array(
		'food'
	),
	'context' => 'normal',
	'priority' => 'high',
	
	'fields' => array(
			array(
					'name' => 'Recipes and Instructions',
					'desc' => '',
					'id' => $prefix . 'food_menu',
					'type' => 'tinymce',
					'tinymce-settings' => array(
							'media_buttons' => true
					),
					'single-valued' => true,
					'single-field' => true
			)
	)
);

/**
 * Directions Meta Box
 */
$meta_boxes[] = array(
	'id' => 'how-to-get-there',
	'title' => 'How to get there',
	'pages' => array(
		'food',
		'travel-activity'
	),
	'context' => 'normal',
	'priority' => 'high',
	
	'fields' => array(
			array(
					'name' => 'Directions',
					'desc' => '',
					'id' => $prefix . 'directions',
					'type' => 'tinymce',
					'tinymce-settings' => array(
							'media_buttons' => true
					),
					'single-valued' => true,
					'single-field' => true
			)
	)
);

/**
 * FB Page/Website Meta Box
 */
$meta_boxes[] = array(
	'id' => 'contact-details',
	'title' => 'Contact Details',
	'pages' => array(
		'food',
		'travel-activity'
	),
	'context' => 'normal',
	'priority' => 'high',
	
	'fields' => array(
			array(
					'name' => 'Facebook Page',
					'desc' => '<i>example: www.facebook.com/antonettebasbas</i>',
					'id' => $prefix . 'fb_page',
					'type' => 'text',
					'single-valued' => true,
					'single-field' => true
			),
			array(
					'name' => 'Website',
					'desc' => '<i>example: www.urbanmeandering.com</i>',
					'id' => $prefix . 'website',
					'type' => 'text',
					'single-valued' => true,
					'single-field' => true
			),
      array(
					'name' => 'Store Hrs.',
					'desc' => '',
					'id' => $prefix . 'store_hrs',
					'type' => 'text',
					'single-valued' => true,
					'single-field' => true
			),
			array(
				'name' => 'Contact Numbers',
				'desc' => '',
				'id' => $prefix . 'contact_numbers',
				'type' => 'multitext',
				'single-valued' => false,
				'single-field' => true
			)
	)
);

/**
 * Must Try Meta Box
 */
$meta_boxes[] = array(
	'id' => 'must-try',
	'title' => 'Must Try',
	'pages' => array(
		'travel-activity'
	),
	'context' => 'side',
	'priority' => 'high',
	
	'fields' => array(
			array(
					'name' => 'Must Try?',
					'desc' => '',
					'id' => $prefix . 'must_try',
					'type' => 'checkbox',
					'single-valued' => true,
					'single-field' => true
			)
	)
);

/**
 * Image carousel Meta Box
 */
$meta_boxes[] = array(
	'id' => 'show_img',
	'title' => 'Image Carousel',
	'pages' => array(
		'img_banner'
	),
	'context' => 'side',
	'priority' => 'high',
	
	'fields' => array(
			array(
					'name' => 'Show image in the Carousel?',
					'desc' => '',
					'id' => $prefix . 'show_img',
					'type' => 'checkbox',
					'single-valued' => true,
					'single-field' => true
			)
	)
);

/**
 * Image carousel Meta Box
 */
$meta_boxes[] = array(
	'id' => 'custom_url',
	'title' => 'Link to',
	'pages' => array(
		'img_banner'
	),
	'context' => 'normal',
	'priority' => 'high',
	
	'fields' => array(
			array(
					'name' => 'URL',
					'desc' => '',
					'id' => $prefix . 'custom_url',
					'type' => 'text',
					'single-valued' => true,
					'single-field' => true
			)
	)
);

//Register all meta boxes
foreach( $meta_boxes as $meta_box )
{
  new UM_Meta_Boxes( $meta_box );
}
